package Network;




import DataStructures.Project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Manuel
 */
public class Connector {
    private String serverURL;

    public Connector(String su) {
        serverURL = su;
    }

    public String sendPostRequest(String data) throws IOException {
        //Build parameter string
            // Construct data
            System.out.println(Thread.currentThread().toString()+"SENDING "+data +" TO "+serverURL);
            String sData = URLEncoder.encode("command", "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8");

            // Send data
            URL url = new URL(serverURL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sData);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String resp = "";
            while ((line = rd.readLine()) != null) {
                // Process line...
                resp += line;
            }
            wr.close();
            rd.close();
            return resp;
       
    }

    public String sendGetRequest(String command, Project data){
        //Build parameter string
        try {

            // Send the request
            URL url = new URL(serverURL+"?command="+command);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("User-Agent", "Mozilla/4.76");
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            System.out.println("---***SENDING***---\n"+data);
            //write parameters

            // Get the response
            String answer = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer +=line;
            };
            reader.close();

            System.out.println("---***RECEIVING***---\n"+answer);
            //return the response
            return answer;

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }


    }

}
